<template>
    <div class="crm-contract-container">
        <el-dialog title="新增合同" v-model="isShowDialog" :close-on-click-modal="false" :style="{ minHeight: '500px' }">
            <el-form ref="addCrmContractFormRef" :model="formData" :rules="formRules" label-width="80px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="业务类别" prop="category">
                            <Dictionary v-model="formData.category" dict-label="crm_project_category" placeholder="请选择业务类别"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12"></el-col>
                    <el-col>
                        <el-form-item label="业务名称" prop="categoryIds">
                            <el-select v-model="formData.categoryIds" multiple filterable remote 
                                @change="handleCrmProjectCategoryChange"
                                @click="loadCrmProjectCategoryData()"
                                :remote-method="loadCrmProjectCategoryData" placeholder="请选择项目业务分类" clearable class="w100">
								<el-option 
									v-for="item in categorys"
									:key="item.id"
									:label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="合同名称" prop="contractName">
                            <el-input v-model="formData.contractName" placeholder="请输入合同名称自动生成" readonly clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="合同编号" prop="contractCode">
                            <el-input v-model="formData.contractCode" placeholder="合同编号系统自动生成" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="合同类型" prop="contractType">
                            <Dictionary v-model="formData.contractType" dict-label="crm_contract_type" placeholder="请选择合同类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="记账类型" prop="accountType" v-if="formData.contractType == '2'">
                            <el-select v-model="formData.accountType" placeholder="请选择记账类型" class="w100">
                                <el-option key="D" label="按天" value="D"></el-option>
                                <el-option key="W" label="按周" value="W"></el-option>
                                <el-option key="M" label="按月" value="M"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="合同金额" prop="contractAmount">
                            <el-input-number v-model="formData.contractAmount" placeholder="请输入合同金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="开始时间" prop="contractStartTime">
                            <el-date-picker v-model="formData.contractStartTime" placeholder="请选择开始时间" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="结束时间" prop="contractEndTime">
                            <el-date-picker v-model="formData.contractEndTime" placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="客户名称" prop="customerId">
                            <el-select v-model="formData.customerId" filterable remote 
                                @change="handleCustomerChange"
                                @click="loadCustomerData()"
                                :remote-method="loadCustomerData" placeholder="请选择关联客户" clearable class="w100">
								<el-option 
									v-for="item in customers"
									:key="item.id"
									:label="item.customerName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="签约日期" prop="signDate">
                            <el-date-picker v-model="formData.signDate" placeholder="请选择签约日期" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="企业名称" prop="enterpriseId">
                            <el-select v-model="formData.enterpriseId" filterable remote 
                                @change="handleEnterpriseChange"
                                @click="loadEnterpriseData()"
                                :remote-method="loadEnterpriseData" placeholder="请选择关联企业" clearable class="w100">
								<el-option 
									v-for="item in enterprises"
									:key="item.id"
									:label="item.enterpriseName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="关联项目" prop="projectIds">
                            <el-select v-model="formData.projectIds" multiple filterable remote 
                                @change="handleProjectChange"
                                @click="loadCrmProjectData()"
                                :remote-method="loadCrmProjectData" placeholder="请选择关联项目，若选择项目业务分类审核通过将自动创建项目关联" clearable class="w100">
								<el-option 
									v-for="item in projects"
									:key="item.id"
									:label="item.projectName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="签约人" prop="signerId">
                            <el-select v-model="formData.signerId" filterable remote 
                                @change="handleSignerChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择签约人" clearable class="w100">
								<el-option 
									v-for="item in signers"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="负责人" prop="ownerId">
                            <el-select v-model="formData.ownerId" filterable remote 
                                @change="handleOwnerChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择负责人" clearable class="w100">
								<el-option 
									v-for="item in owners"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
						<el-form-item label="备注">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
                    <el-col>
                        <el-form-item label="合同文件" prop="attachments">
                            <Storage :model="attachment" @success="onUploadSuccess" @remove="onUploadRemove"></Storage>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addCrmContract } from '/@/api/crm/contract/index';
import { getCrmCustomerList, getCrmCustomer } from '/@/api/crm/customer/index';
import { getCrmProjectList } from '/@/api/crm/project/index';
import { getCrmUserList } from '/@/api/crm/user/index';
import { getCrmEnterpriseList, getCrmEnterprise } from '/@/api/crm/enterprise/index';
import { getCrmProjectCategoryList } from '/@/api/crm/project/category/index';
import Dictionary from '/@/components/dictionary/index.vue';
import Storage from '/@/views/crm/components/storage/index.vue';
import { get } from 'sortablejs';

export default {
    name: 'crm/contract/add',
    components: { Dictionary, Storage },
    setup(props, context) {
        
        const validContractCustomerNotEmpty = (rule, value, callback) => {
            const {  customerId, enterpriseId } = state.formData;
            if(customerId == undefined && enterpriseId == undefined){
                return callback(new Error('客户名称和企业名称不能同时为空'));
            }else{
                return callback();
            }
        }

        const validContractTimeNotEmpty = (rule, value, callback) => {
            const { contractType, contractStartTime, contractEndTime } = state.formData;
            if(contractType == 2){
                if(contractStartTime == undefined || contractEndTime == undefined){
                    return callback(new Error('合同开始和结束时间不能为空'));
                }else{
                    return callback();
                }
            }else{
                return callback();
            }
        }

        const validAttachmentNotEmpty = (rule, value, callback) => {
            const { attachments } = state.formData;
            if(attachments == undefined || attachments.length == 0){
                return callback(new Error('合同文件不能为空'));
            }else{
                return callback();
            }
        }
        const addCrmContractFormRef = ref();
        const state = reactive({
            isShowDialog: false,
            projects: [],
            customers: [],
            enterprises: [],
            signers: [],
            owners: [],
            categorys: [],
            attachment: {
                upload:{
                    limit: 20,
                    accept: '.jpg,.png,.svg,.webp,.gif,.pdf',
                    images: []
                }
            },
            formData: {
                contractName: undefined,
                category: undefined,
                categorys: [],
                categoryIds: [],
                attachments: [],
            },
            formRules : {
                categoryIds: { required: true, message: '业务名称不能为空', trigger: 'blur' },
                contractName: { required: true, message: '合同名称不能为空', trigger: 'blur' },
                contractType: { required: true, message: '合同类型不能为空', trigger: 'blur' },
                accountType: { required: true, message: '记账类型不能为空', trigger: 'blur' },
                contractAmount: { required: true, message: '合同金额不能为空', trigger: 'blur' },
                customerId: { validator: validContractCustomerNotEmpty, trigger: 'blur' },
                enterpriseId: { validator: validContractCustomerNotEmpty, trigger: 'blur' },
                ownerId: { required: true, message: '负责人不能为空', trigger: 'blur' },
                contractStartTime: { validator: validContractTimeNotEmpty, trigger: 'blur' },
                contractEndTime: { validator: validContractTimeNotEmpty, trigger: 'blur' },
                attachments: { validator: validAttachmentNotEmpty, trigger: 'blur' },
            }
        });
        
        const loadCrmProjectCategoryData = (query?: string) => {
            if(query == '') return;
            getCrmProjectCategoryList({name: query, category: state.formData?.category}).then((res) => {
                if(res.code == 0){
                    state.categorys = res.data;
                }
            });
        }
        const handleCrmProjectCategoryChange = (categoryIds) => {
            // 创建一个新的无重复类别的数组，并且只包含有效的类别对象
            const selectedCategories = categoryIds.map(id => state.categorys.find(item => item.id === id)).filter(Boolean);

            // 使用一个 Set 来存储已经存在的 category id，用于去重
            const existingCategoryIds = new Set(state.formData.categorys.map(item => item.id));

            // 过滤出新增加的类别（即不在现有类别中的类别）
            const newCategories = selectedCategories.filter(category => !existingCategoryIds.has(category.id));

            // 更新 formData 中的 categories，但保持原始顺序
            state.formData.categorys.push(...newCategories);

            // 清空 contractName 并重新构建，确保不重复
            const uniqueNames = [...new Set(state.formData.categorys.map(item => item.name))]; // 使用Set去除重复名字

            // 使用 join 方法来创建 contractName 字符串
            state.formData.contractName = uniqueNames.join(";");
        }

        const loadCrmProjectData = (query?: string) => {
            if(query == '') return;
            getCrmProjectList({projectName: query, examineStatus: '2', contractId: 'null'}).then((res) => {
                if(res.code == 0){
                    state.projects = res.data;
                }
            });
        }

        // 加载客户数据
        const loadCustomerData = (query?: string) => {
            if(state.formData.enterpriseId){
                getCrmEnterprise({id: enterpriseId}).then((res) => {
                    if(res.code == 0){
                        state.customers = res.data.customers;
                    }
                });
            }else{
                if(query == '') return;
                getCrmCustomerList({customerName: query}).then((res) => {
                    if(res.code == 0){
                        state.customers = res.data;
                    }
                });
            }
        }

        // 加载企业数据
        const loadEnterpriseData = (query?: string) => {
            if(state.formData.customerId){
                getCrmCustomer({id: customerId}).then((res) => {
                    if(res.code == 0){
                        state.enterprises = res.data.enterprises;
                    }
                });
            }else{
                if(query == '') return;
                getCrmEnterpriseList({enterpriseName: query}).then((res) => {
                    if(res.code == 0){
                        state.enterprises = res.data;
                    }
                });
            }
        }

        const handleProjectChange = (projectId) => {
            // const project = state.projects.find(item => item.id == projectId);
            // if(state.formData.contractName == undefined){
            //     state.formData.contractName = project?.projectName;
            // }
        }

        const handleCustomerChange = (customerId) => {
            const customer = state.customers.find(item => item.id == customerId);
            state.formData.customerId = customer?.id;
            state.formData.customerName = customer?.customerName;
            getCrmCustomer({id: customerId}).then((res) => {
                if(res.code == 0){
                    state.enterprises = res.data.enterprises;
                }
            });
        }
        const handleEnterpriseChange = (enterpriseId) => {
            const enterprise = state.enterprises.find(item => item.id == enterpriseId);
            state.formData.enterpriseId = enterprise?.id;
            state.formData.enterpriseName = enterprise?.enterpriseName;
            getCrmEnterprise({id: enterpriseId}).then((res) => {
                if(res.code == 0){
                    state.customers = res.data.customers;
                }
            });
        }

        const loadCrmUserData = (query?: string) => {
            if(query == '') return;
            getCrmUserList({userName: query}).then((res) => {
                if(res.code == 0){
                    state.signers = res.data;
                    state.owners = res.data;
                }
            });
        }
        const handleSignerChange = (signerId) => {
            const signer = state.signers.find(item => item.id == signerId);
            state.formData.signerId = signer?.id;
            state.formData.signerName = signer?.userName;
        }
        const handleOwnerChange = (ownerId) => {
            const owner = state.owners.find(item => item.id == ownerId);
            state.formData.ownerId = owner?.id;
            state.formData.ownerName = owner?.userName;
        }

        const onUploadSuccess = (file, urls) => {
            state.formData?.attachments.push({url: file.url, name: file.name});
        };

        const onUploadRemove = (file, urls) => {
            const index = state.formData?.attachments.findIndex((item) => item.url == file.url);
            if(index > -1){
				state.formData?.attachments.splice(index, 1);
			}
        };

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addCrmContractFormRef.value.resetFields();
            state.attachment.upload.images = [];
            state.formData.categoryIds = [];
            state.formData.categorys = [];
            state.formData.attachments = [];
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addCrmContractFormRef.value.validate(valid => {
                if(valid){
                    const uniqueNames = [...new Set(state.formData.categorys.map(item => item.name))];
                    state.formData.contractName = uniqueNames.join(";");
                    let params = {
                        contractName: state.formData.contractName,
                        contractType: state.formData.contractType,
                        accountType: state.formData.accountType,
                        contractCode: state.formData.contractCode,
                        contractAmount: state.formData.contractAmount,
                        customerId: state.formData.customerId,
                        customerName: state.formData.customerName,
                        contractStartTime: state.formData.contractStartTime,
                        contractEndTime: state.formData.contractEndTime,
                        signDate: state.formData.signDate,
                        enterpriseId: state.formData.enterpriseId,
                        enterpriseName: state.formData.enterpriseName,
                        signerId: state.formData.signerId,
                        signerName: state.formData.signerName,
                        ownerId: state.formData.ownerId,
                        ownerName: state.formData.ownerName,
                        remark: state.formData.remark,
                        projectIds: state.formData.projectIds,
                        categoryIds: state.formData.categoryIds,
                        attachments: state.formData.attachments,
                    }
                    addCrmContract(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            addCrmContractFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadCustomerData,
            handleCustomerChange,
            loadEnterpriseData,
            handleEnterpriseChange,
            loadCrmUserData,
            handleProjectChange,
            handleSignerChange,
            handleOwnerChange,
            loadCrmProjectData,
            onUploadSuccess,
            onUploadRemove,
            loadCrmProjectCategoryData,
            handleCrmProjectCategoryChange,
            ...toRefs(state),
        };
    },
};
</script>